package com.heba.adapter.diary;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.heba.Cfg;
import com.heba.bean.PhotoObject;
import com.heba.bean.diary.ItemDiaryDetailObject;
import com.heba.bean.diary.ItemDiaryImageObject;
import com.heba.bean.diary.ItemPasteObject;
import com.heba.bean.product.ItemProductImageObject;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.R;
import com.heba.greenmulu.ZoomPhotoActivity;
import com.heba.greenmulu.diary.VideoPlayNetworkActivity;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.view.DiaryImageShowLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 日記圖片大圖顯示
 * <p>
 * Created by xingbao on 2019/2/12.
 */

public class DiaryImageShowPagerAdapter extends PagerAdapter {

    private Context context;
    private List<ItemDiaryImageObject> list;
    private ItemDiaryDetailObject data;
    private int position;
    private int width;  //图片显示的宽度
    private ImageView iv_like;
    long mLastTime=0;
    long mCurTime=0;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
//                    Toast.makeText(context,"这是单击事件",Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    MessageEvent event = new MessageEvent();
                    event.setEvent("DoubleClickToLike");
                    event.setPosition(position);
                    event.setDiaryDetailObject(data);
                    EventBus.getDefault().post(event);
                    break;
            }
        }
    };
    public DiaryImageShowPagerAdapter(Context context, List<ItemDiaryImageObject> list) {
        this.context = context;
        this.list = list;
        this.width = DensityUtils.getWidth(context);
    }
    public DiaryImageShowPagerAdapter(Context context, List<ItemDiaryImageObject> list,ItemDiaryDetailObject data,int pos,ImageView iv_like) {

        this.context = context;
        this.list = list;
        this.width = DensityUtils.getWidth(context);
        this.data = data;
        this.position = pos;
        this.iv_like = iv_like;
    }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        container.removeView((View) object);
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        return POSITION_NONE;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        View view = LayoutInflater.from(context).inflate(R.layout.item_diary_image_show, null);
        DiaryImageShowLayout layoutContent = view.findViewById(R.id.layoutContent);
        ImageView imageView = view.findViewById(R.id.imageView);
        ImageView iv_show_tag = view.findViewById(R.id.iv_show_tag);

        layoutContent.setVisibility(View.GONE);
        imageView.setVisibility(View.VISIBLE);
        iv_show_tag.setVisibility(View.GONE);

        ItemDiaryImageObject object = list.get(position);
        List<ItemPasteObject> pasteObjects = object.getPaste();

        //显示图片
        GlideUtil.loadImageWithDefaultPlaceHolder(context, object.getImageUrl(), imageView);

        if (null == pasteObjects || pasteObjects.isEmpty()) {
            //没有标记任何用户
//            imageView.setVisibility(View.VISIBLE);
        } else {
            //图片标记了用户
            iv_show_tag.setVisibility(View.VISIBLE);
            try {
                int imageWidth = Integer.parseInt(object.getImageWidth());
                int imageHeight = Integer.parseInt(object.getImageHeight());
                float scale = (float) imageHeight / (float) imageWidth;
                int height = (int) (width * scale);
                layoutContent.setImgBg(width, height, object);
                layoutContent.setVisibility(View.VISIBLE);
            } catch (Exception e) {
                layoutContent.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
                GlideUtil.loadImageWithDefaultPlaceHolder(context, object.getImageUrl(), imageView);
                e.printStackTrace();
            }
        }

        /**
         * 显示标记的用户标签
         */
        iv_show_tag.setOnClickListener(v -> {
            imageView.setVisibility(imageView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
        });

        /**
         * 跳转视频还是显示图片大图
         */
        imageView.setOnClickListener(v -> {
            if (!list.isEmpty()) {
                ItemDiaryImageObject diaryImageObject = list.get(0);
                if (object.getType() == 1 && object.getVideoUrl() != null) {
                    //跳转视频播放页面
                    Bundle bundle = new Bundle();
                    bundle.putInt(CommonConfig.TYPE, 1);
                    bundle.putString(CommonConfig.DIARY_IMAGE, diaryImageObject.getImageUrl());
                    bundle.putString(CommonConfig.DIARY_VIDEO, diaryImageObject.getVideoUrl());
                    openActivity(VideoPlayNetworkActivity.class, bundle);
                } else {

                    mLastTime=mCurTime;
                    mCurTime= System.currentTimeMillis();
                    if(mCurTime-mLastTime<300){//双击事件
                        mCurTime =0;
                        mLastTime = 0;
                        handler.removeMessages(1);
                        handler.sendEmptyMessage(2);

                        if (!Cfg.UserID.equals(data.getUserID())) {
                            int type = data.getIsLiked()==0?0:1;
                            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                                @Override
                                public void Success() {
                                    if (data.getIsLiked() == 1) {
                                        data.setIsLiked(0);
                                        data.setLikeCount(data.getLikeCount() - 1);
                                        iv_like.setSelected(false);
                                    } else {
                                        data.setIsLiked(1);
                                        data.setLikeCount(data.getLikeCount() + 1);
                                        iv_like.setSelected(true);
                                    }

                                }

                                @Override
                                public void Fail(String error) {

                                }
                            }).diaryLike(context, data.getDiaryID(), type);
                        }

                    }else{//单击事件
                        handler.sendEmptyMessageDelayed(1, 310);
                    }
                }
            }
        });

        container.addView(view);
        return view;
    }

    /**
     * 跳转activity
     *
     * @param pClass
     * @param pBundle
     */
    private void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(context, pClass);
        intent.putExtras(pBundle);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    /**
     * 跳转activity
     *
     * @param pClass
     * @param pBundle
     */
    private void openActivityWithFadeInAnimation(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(context, pClass);
        intent.putExtras(pBundle);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }


}
